// CFS Web System - 主JavaScript文件

// 全局配置
const CFS = {
    config: {
        apiBaseUrl: '/api/',
        maxFileSize: 50 * 1024 * 1024, // 50MB
        allowedExtensions: ['.xlsx', '.xls', '.csv', '.txt'],
        uploadChunkSize: 1024 * 1024, // 1MB
        pollInterval: 2000 // 2秒
    },
    
    // 工具函数
    utils: {
        // 格式化文件大小
        formatFileSize: function(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        },
        
        // 格式化日期时间
        formatDateTime: function(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        },
        
        // 显示通知 - 使用Bootstrap Toast
        showNotification: function(message, type = 'info', duration = 5000) {
            const toastId = 'toast-' + Date.now();
            const iconClass = {
                'success': 'bi-check-circle-fill text-success',
                'error': 'bi-exclamation-triangle-fill text-danger',
                'warning': 'bi-exclamation-triangle-fill text-warning',
                'info': 'bi-info-circle-fill text-info'
            }[type] || 'bi-info-circle-fill text-info';
            
            const toastHtml = `
                <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="toast-header">
                        <i class="bi ${iconClass} me-2"></i>
                        <strong class="me-auto">${type === 'success' ? '成功' : type === 'error' ? '错误' : type === 'warning' ? '警告' : '提示'}</strong>
                        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                    <div class="toast-body">
                        ${message}
                    </div>
                </div>
            `;
            
            // 查找Toast容器
            let container = document.querySelector('.toast-container');
            if (!container) {
                container = document.createElement('div');
                container.className = 'toast-container position-fixed top-0 end-0 p-3';
                container.style.zIndex = '11000';
                document.body.appendChild(container);
            }
            
            // 添加Toast
            const toastElement = document.createElement('div');
            toastElement.innerHTML = toastHtml;
            const toast = toastElement.firstElementChild;
            container.appendChild(toast);
            
            // 初始化并显示Toast
            const bsToast = new bootstrap.Toast(toast, {
                delay: duration
            });
            bsToast.show();
            
            // 监听Toast隐藏事件，移除DOM元素
            toast.addEventListener('hidden.bs.toast', function() {
                toast.remove();
            });
            
            return bsToast;
        },
        
        // 显示加载状态
        showLoading: function(element, text = '加载中...') {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }
            
            if (element) {
                element.innerHTML = `
                    <div class="d-flex align-items-center justify-content-center p-3">
                        <div class="loading-spinner me-2"></div>
                        <span>${text}</span>
                    </div>
                `;
            }
        },
        
        // 隐藏加载状态
        hideLoading: function(element) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }
            
            if (element) {
                const spinner = element.querySelector('.loading-spinner');
                if (spinner) {
                    spinner.parentElement.remove();
                }
            }
        },
        
        // AJAX请求封装
        ajax: function(options) {
            const defaults = {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.getCsrfToken()
                },
                credentials: 'same-origin'
            };
            
            const config = Object.assign({}, defaults, options);
            
            return fetch(config.url, config)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .catch(error => {
                    console.error('AJAX请求失败:', error);
                    throw error;
                });
        },
        
        // 获取CSRF Token
        getCsrfToken: function() {
            const token = document.querySelector('[name=csrfmiddlewaretoken]');
            return token ? token.value : '';
        },
        
        // 验证文件
        validateFile: function(file) {
            const errors = [];
            
            // 检查文件大小
            if (file.size > CFS.config.maxFileSize) {
                errors.push(`文件大小超过限制 (${CFS.utils.formatFileSize(CFS.config.maxFileSize)})`);
            }
            
            // 检查文件扩展名
            const extension = '.' + file.name.split('.').pop().toLowerCase();
            if (!CFS.config.allowedExtensions.includes(extension)) {
                errors.push(`不支持的文件格式: ${extension}`);
            }
            
            return {
                valid: errors.length === 0,
                errors: errors
            };
        }
    },
    

    
    // 任务管理模块
    taskManager: {
        // 初始化任务管理
        init: function() {
            this.loadTaskList();
            this.startPolling();
        },
        
        // 加载任务列表
        loadTaskList: function() {
            const taskList = document.querySelector('#task-list');
            if (!taskList) return;
            
            CFS.utils.showLoading(taskList, '加载任务列表...');
            
            CFS.utils.ajax({
                url: '/data-processing/ajax/tasks/',
                method: 'GET'
            })
            .then(data => {
                if (data.success) {
                    this.renderTaskList(data.tasks);
                } else {
                    taskList.innerHTML = '<div class="alert alert-danger">加载失败: ' + data.error + '</div>';
                }
            })
            .catch(error => {
                taskList.innerHTML = '<div class="alert alert-danger">加载失败: ' + error.message + '</div>';
            });
        },
        
        // 渲染任务列表
        renderTaskList: function(tasks) {
            const taskList = document.querySelector('#task-list');
            if (!taskList) return;
            
            if (tasks.length === 0) {
                taskList.innerHTML = '<div class="alert alert-info">暂无任务</div>';
                return;
            }
            
            const html = tasks.map(task => `
                <div class="card mb-3 task-item" data-task-id="${task.id}">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-md-4">
                                <h6 class="mb-1">${task.name}</h6>
                                <small class="text-muted">模板: ${task.template_name || '未指定'}</small>
                            </div>
                            <div class="col-md-3">
                                <span class="status-badge status-${task.status}">${task.status_display}</span>
                            </div>
                            <div class="col-md-3">
                                ${task.status === 'processing' ? `
                                    <div class="progress" style="height: 20px;">
                                        <div class="progress-bar" role="progressbar" style="width: ${task.progress || 0}%">
                                            ${task.progress || 0}%
                                        </div>
                                    </div>
                                ` : `
                                    <small class="text-muted">
                                        创建时间: ${CFS.utils.formatDateTime(task.created_at)}
                                    </small>
                                `}
                            </div>
                            <div class="col-md-2 text-end">
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary view-task" data-task-id="${task.id}">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    ${task.status === 'completed' ? `
                                        <button type="button" class="btn btn-outline-success download-result" data-task-id="${task.id}">
                                            <i class="fas fa-download"></i>
                                        </button>
                                    ` : ''}
                                    ${task.status === 'failed' || task.status === 'pending' ? `
                                        <button type="button" class="btn btn-outline-danger delete-task" data-task-id="${task.id}">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    ` : ''}
                                </div>
                            </div>
                        </div>
                        ${task.error_message ? `
                            <div class="mt-2">
                                <small class="text-danger">
                                    <i class="fas fa-exclamation-triangle"></i> ${task.error_message}
                                </small>
                            </div>
                        ` : ''}
                    </div>
                </div>
            `).join('');
            
            taskList.innerHTML = html;
            
            // 绑定事件
            this.bindTaskEvents();
        },
        
        // 绑定任务事件
        bindTaskEvents: function() {
            // 查看任务详情
            document.querySelectorAll('.view-task').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const taskId = e.target.closest('button').dataset.taskId;
                    this.viewTaskDetail(taskId);
                });
            });
            
            // 下载结果
            document.querySelectorAll('.download-result').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const taskId = e.target.closest('button').dataset.taskId;
                    this.downloadResult(taskId);
                });
            });
            
            // 删除任务
            document.querySelectorAll('.delete-task').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const taskId = e.target.closest('button').dataset.taskId;
                    this.deleteTask(taskId);
                });
            });
        },
        
        // 查看任务详情
        viewTaskDetail: function(taskId) {
            // 实现任务详情查看逻辑
            console.log('查看任务详情:', taskId);
        },
        
        // 下载结果
        downloadResult: function(taskId) {
            window.location.href = `/excel-processor/download/${taskId}/`;
        },
        
        // 删除任务
        deleteTask: function(taskId) {
            if (!confirm('确定要删除这个任务吗？')) {
                return;
            }
            
            CFS.utils.ajax({
                url: `/data-processing/ajax/tasks/${taskId}/delete/`,
                method: 'DELETE'
            })
            .then(data => {
                if (data.success) {
                    CFS.utils.showNotification('任务删除成功', 'success');
                    this.loadTaskList();
                } else {
                    CFS.utils.showNotification('删除失败: ' + data.error, 'error');
                }
            })
            .catch(error => {
                CFS.utils.showNotification('删除失败: ' + error.message, 'error');
            });
        },
        
        // 开始轮询
        startPolling: function() {
            setInterval(() => {
                const processingTasks = document.querySelectorAll('.status-processing');
                if (processingTasks.length > 0) {
                    this.loadTaskList();
                }
            }, CFS.config.pollInterval);
        }
    },
    
    // 文件管理模块
    fileManager: {
        // 初始化文件管理
        init: function() {
            this.loadFileList();
            this.setupFilters();
        },
        
        // 加载文件列表
        loadFileList: function() {
            const fileList = document.querySelector('#file-list-container');
            if (!fileList) return;
            
            CFS.utils.showLoading(fileList, '加载文件列表...');
            
            const params = new URLSearchParams();
            const fileType = document.querySelector('#file-type-filter')?.value;
            const templateId = document.querySelector('#template-filter')?.value;
            
            if (fileType) params.append('file_type', fileType);
            if (templateId) params.append('template_id', templateId);
            
            CFS.utils.ajax({
                url: '/file-manager/ajax/files/?' + params.toString(),
                method: 'GET'
            })
            .then(data => {
                if (data.success) {
                    this.renderFileList(data.files);
                } else {
                    fileList.innerHTML = '<div class="alert alert-danger">加载失败: ' + data.error + '</div>';
                }
            })
            .catch(error => {
                fileList.innerHTML = '<div class="alert alert-danger">加载失败: ' + error.message + '</div>';
            });
        },
        
        // 渲染文件列表
        renderFileList: function(files) {
            const container = document.querySelector('#file-list-container');
            if (!container) return;
            
            if (files.length === 0) {
                container.innerHTML = '<div class="alert alert-info">暂无文件</div>';
                return;
            }
            
            const html = files.map(file => `
                <div class="card mb-3 file-item" data-file-id="${file.id}">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-md-4">
                                <h6 class="mb-1">${file.original_name}</h6>
                                <small class="text-muted">${file.file_type} | ${CFS.utils.formatFileSize(file.file_size)}</small>
                            </div>
                            <div class="col-md-3">
                                <small class="text-muted">
                                    模板: ${file.template_name || '未关联'}
                                </small>
                            </div>
                            <div class="col-md-3">
                                <small class="text-muted">
                                    上传时间: ${CFS.utils.formatDateTime(file.created_at)}
                                </small>
                            </div>
                            <div class="col-md-2 text-end">
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary preview-file" data-file-id="${file.id}">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-success download-file" data-file-id="${file.id}">
                                        <i class="fas fa-download"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-danger delete-file" data-file-id="${file.id}">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
            
            container.innerHTML = html;
            
            // 绑定事件
            this.bindFileEvents();
        },
        
        // 绑定文件事件
        bindFileEvents: function() {
            // 预览文件
            document.querySelectorAll('.preview-file').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const fileId = e.target.closest('button').dataset.fileId;
                    this.previewFile(fileId);
                });
            });
            
            // 下载文件
            document.querySelectorAll('.download-file').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const fileId = e.target.closest('button').dataset.fileId;
                    this.downloadFile(fileId);
                });
            });
            
            // 删除文件
            document.querySelectorAll('.delete-file').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const fileId = e.target.closest('button').dataset.fileId;
                    this.deleteFile(fileId);
                });
            });
        },
        
        // 预览文件
        previewFile: function(fileId) {
            // 实现文件预览逻辑
            console.log('预览文件:', fileId);
        },
        
        // 下载文件
        downloadFile: function(fileId) {
            window.location.href = `/file-manager/api/file-manager/${fileId}/download_file/`;
        },
        
        // 删除文件
        deleteFile: function(fileId) {
            if (!confirm('确定要删除这个文件吗？')) {
                return;
            }
            
            CFS.utils.ajax({
                url: `/file-manager/api/file-manager/${fileId}/delete_file/`,
                method: 'DELETE'
            })
            .then(data => {
                if (data.success) {
                    CFS.utils.showNotification('文件删除成功', 'success');
                    this.loadFileList();
                } else {
                    CFS.utils.showNotification('删除失败: ' + data.error, 'error');
                }
            })
            .catch(error => {
                CFS.utils.showNotification('删除失败: ' + error.message, 'error');
            });
        },
        
        // 设置过滤器
        setupFilters: function() {
            const fileTypeFilter = document.querySelector('#file-type-filter');
            const templateFilter = document.querySelector('#template-filter');
            
            if (fileTypeFilter) {
                fileTypeFilter.addEventListener('change', () => {
                    this.loadFileList();
                });
            }
            
            if (templateFilter) {
                templateFilter.addEventListener('change', () => {
                    this.loadFileList();
                });
            }
        }
    }
};

// 全局Toast函数，方便在各个页面中使用
window.showToast = function(message, type = 'info', duration = 5000) {
    return CFS.utils.showNotification(message, type, duration);
};

// 兼容旧的alert调用
window.showSuccess = function(message) {
    return showToast(message, 'success');
};

window.showError = function(message) {
    return showToast(message, 'error');
};

window.showWarning = function(message) {
    return showToast(message, 'warning');
};

window.showInfo = function(message) {
    return showToast(message, 'info');
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 根据页面类型初始化相应模块
    const currentPage = document.body.dataset.page;
    
    switch (currentPage) {

        case 'task-list':
            CFS.taskManager.init();
            break;
        case 'file-manager':
            CFS.fileManager.init();
            break;
        default:
            // 通用初始化
            break;
    }
    
    // 添加页面动画
    document.body.classList.add('fade-in');
});

// 导出全局对象
window.CFS = CFS;